import java.util.Stack;
import java.util.Scanner;

public class BracketValidator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入包含括号的字符串：");
        String input = scanner.nextLine();

        if (isValidBrackets(input)) {
            System.out.println("匹配成功");
        } else {
            System.out.println("匹配失败");
        }
    }

    public static boolean isValidBrackets(String s) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char current = s.charAt(i);

            // 如果是左括号，压入栈中
            if (isLeftBracket(current)) {
                stack.push(current);
            }
            // 如果是右括号
            else if (isRightBracket(current)) {
                // 栈为空，说明没有对应的左括号
                if (stack.isEmpty()) {
                    return false;
                }

                // 弹出栈顶元素并检查是否匹配
                char top = stack.pop();
                if (!bracketsMatch(top, current)) {
                    return false;
                }
            }
            // 其他字符忽略
        }

        // 检查栈是否为空（所有左括号都有匹配）
        return stack.isEmpty();
    }

    // 判断是否为左括号
    private static boolean isLeftBracket(char c) {
        return c == '(' || c == '{' || c == '[';
    }

    // 判断是否为右括号
    private static boolean isRightBracket(char c) {
        return c == ')' || c == '}' || c == ']';
    }

    // 判断左右括号是否匹配
    private static boolean bracketsMatch(char left, char right) {
        switch (left) {
            case '(': return right == ')';
            case '{': return right == '}';
            case '[': return right == ']';
            default: return false;
        }
    }
}